<?php

namespace App\Scopes;

use App\Models\Apply;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

/**
 * 根据报名项目的特殊需求，定制化
 * 智库，很据组别apply，筛选
 * 非智库，根据省份筛选
 *
 * Created by PhpStorm.
 * User: lyndon
 * Date: 17-6-16
 * Time: 下午2:03
 */
class ApplyScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  Builder $builder
     * @param  Model $model
     * @return Builder
     */
    public function apply(Builder $builder, Model $model)
    {
        $user = getUser();
        if (isset($user) && $user->isAdmin()) {
            return $builder;
        }
        if (empty($user)) {
            $openid = getOpenid();
            return $builder->where('openid', $openid);
        }
        $apply = [];
        $provinces = [];
        $provinceStart = strlen(Permission::PROVINCE_PRE);
        $applyStart = strlen(Permission::APPLY_PRE);
        foreach ($user->getPermissions() as $userPermission) {
            if (starts_with($userPermission->slug, Permission::PROVINCE_PRE)) {
                $provinces[] = substr($userPermission->slug, $provinceStart);
            }
            if (starts_with($userPermission->slug, Permission::APPLY_PRE)) {
                $apply[] = intval(substr($userPermission->slug, $applyStart));
            }
        }

        return $builder->whereIn('apply', $apply)
            ->orWhere(function ($query) use ($provinces) {
                $query->whereIn('apply', Apply::$notThinkTank)->whereIn('province', $provinces);
            });

    }
}